<template>
  <div class="pdf-viewer">
    <div class="header">
      <span>{{ title }}</span>
      <div class="page-controls">
        <button @click="prevPage" :disabled="currentPage <= 1">上一页</button>
        <div class="page-jump">
          <input
            type="number"
            v-model="pageInput"
            :min="1"
            :max="totalPages"
            @keyup.enter="jumpToPage"
          />
          <span>/ {{ totalPages }}</span>
        </div>
        <button @click="nextPage" :disabled="currentPage >= totalPages">
          下一页
        </button>
        <button @click="toggleFullScreen" class="fullscreen-btn">
          {{ isFullScreen ? "退出全屏" : "全屏" }}
        </button>
      </div>
    </div>
    <div class="pdf-container" ref="pdfContainer">
      <canvas ref="pdfCanvas"></canvas>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRoute } from "vue-router";
import * as pdfjsLib from "pdfjs-dist";
import pdfWorker from "pdfjs-dist/build/pdf.worker.mjs?url";

// 使用 Vite 的方式导入 worker
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfWorker;

const route = useRoute();
const title = ref("");
const pdfCanvas = ref(null);
const scale = ref(1.5);
const currentPage = ref(1);
const totalPages = ref(1);
const pdfContainer = ref(null);
const pageInput = ref(1);
const isFullScreen = ref(false);
let pdfDoc = null;

async function renderPdf(url) {
  try {
    console.log("Attempting to load PDF:", url);
    
    // Handle different URL types
    let pdfUrl = url;
    
    // If the URL has special characters or is malformed, try to decode it properly
    if (url.includes('%')) {
      try {
        pdfUrl = decodeURIComponent(url);
        console.log("Decoded URL:", pdfUrl);
      } catch (e) {
        console.warn("Error decoding URL, using original:", e);
      }
    }
    
    // Try loading with fetch + arraybuffer approach first
    try {
      console.log("Trying fetch + arraybuffer method...");
      // Fetch the PDF as arraybuffer
      const response = await fetch(pdfUrl);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const pdfData = await response.arrayBuffer();
      
      // Load the PDF using the binary data directly
      const loadingTask = pdfjsLib.getDocument({
        data: pdfData,
        cMapUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/cmaps/',
        cMapPacked: true,
      });
      
      // Add progress callback to monitor loading
      loadingTask.onProgress = function(progressData) {
        if (progressData.total > 0) {
          console.log(`Loading: ${Math.round((progressData.loaded / progressData.total) * 100)}%`);
        }
      };
      
      pdfDoc = await loadingTask.promise;
      totalPages.value = pdfDoc.numPages;
      
      await renderPage(currentPage.value);
      console.log("PDF loaded successfully with fetch method");
    } catch (fetchError) {
      console.error("Fetch method failed:", fetchError);
      
      try {
        console.log("Trying direct URL method...");
        // Fallback to direct URL method
        const loadingTask = pdfjsLib.getDocument({
          url: pdfUrl,
          cMapUrl: 'https://unpkg.com/pdfjs-dist@3.11.174/cmaps/',
          cMapPacked: true,
        });
        
        pdfDoc = await loadingTask.promise;
        totalPages.value = pdfDoc.numPages;
        
        await renderPage(currentPage.value);
        console.log("PDF loaded successfully with direct URL method");
      } catch (directError) {
        throw new Error(`Direct URL method also failed: ${directError.message}`);
      }
    }
  } catch (error) {
    console.error("All PDF loading methods failed:", error);
    alert("无法加载PDF文件，请检查URL是否正确或联系管理员。");
  }
}

async function renderPage(pageNum) {
  try {
    const page = await pdfDoc.getPage(pageNum);
    const viewport = page.getViewport({ scale: scale.value });
    const canvas = pdfCanvas.value;
    const context = canvas.getContext("2d");

    canvas.height = viewport.height;
    canvas.width = viewport.width;

    const renderContext = {
      canvasContext: context,
      viewport: viewport,
    };

    await page.render(renderContext);
    pageInput.value = pageNum;
  } catch (error) {
    console.error("Error rendering page:", error);
  }
}

async function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    await renderPage(currentPage.value);
  }
}

async function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--;
    await renderPage(currentPage.value);
  }
}

// 跳转到指定页面
async function jumpToPage() {
  const pageNum = parseInt(pageInput.value);
  if (pageNum && pageNum >= 1 && pageNum <= totalPages.value) {
    currentPage.value = pageNum;
    await renderPage(pageNum);
  } else {
    pageInput.value = currentPage.value;
  }
}

// 全屏切换
async function toggleFullScreen() {
  if (!document.fullscreenElement) {
    await pdfContainer.value.requestFullscreen();
    isFullScreen.value = true;
  } else {
    await document.exitFullscreen();
    isFullScreen.value = false;
  }
}

// 添加滚轮事件处理函数
function handleWheel(event) {
  if (isFullScreen.value) {
    if (event.deltaY > 0) {
      nextPage();
    } else {
      prevPage();
    }
    event.preventDefault();
  }
}

// Clean up resources
function cleanup() {
  if (pdfDoc) {
    try {
      pdfDoc.destroy();
      pdfDoc = null;
    } catch (err) {
      console.error("Error destroying PDF document:", err);
    }
  }
}

onMounted(() => {
  // Get PDF URL from query parameter without decoding it yet
  // The renderPdf function will handle decoding if needed
  const url = route.query.url || '';
  title.value = route.query.title || "";
  renderPdf(url);

  // Add full screen change listener
  document.addEventListener("fullscreenchange", () => {
    isFullScreen.value = !!document.fullscreenElement;
  });

  // Add wheel event listener
  pdfContainer.value.addEventListener("wheel", handleWheel, { passive: false });
});

onBeforeUnmount(() => {
  cleanup();
  // Remove event listeners
  document.removeEventListener("fullscreenchange", () => {
    isFullScreen.value = !!document.fullscreenElement;
  });
  
  if (pdfContainer.value) {
    pdfContainer.value.removeEventListener("wheel", handleWheel);
  }
});
</script>

<style scoped>
.pdf-viewer {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e8e8e8;
}

.pdf-container {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: #e0e0e0;
}

canvas {
  background-color: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.page-controls {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
}

.page-controls button {
  padding: 4px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
}

.page-controls button:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-jump {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-jump input {
  width: 50px;
  padding: 4px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  text-align: center;
}

.fullscreen-btn {
  margin-left: 10px;
  background-color: #1890ff;
  color: rgb(31, 2, 2);
  border: none;
}

.fullscreen-btn:hover {
  background-color: #40a9ff;
}

/* 全屏时的样式 */
.pdf-container:fullscreen {
  background-color: white;
  padding: 0;
}

.pdf-container:fullscreen canvas {
  max-height: 100vh;
  max-width: 100vw;
  object-fit: contain;
}

/* 移除输入框的箭头按钮 */
.page-jump input::-webkit-outer-spin-button,
.page-jump input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.page-jump input[type="number"] {
  -moz-appearance: textfield;
}
</style>
